<template>
    <div class="amap-page-container">
        <iframe :src="apiUrl" class="amap-address" id="amap-address"></iframe>
    </div>
</template>

<style scoped lang="stylus">
    .amap-demo, .amap-page-container
        height: 300px;
        font-size:0.3rem;
    .amap-address {
        width: 100%;
    }
</style>

<script>
  import {amapKey} from './config';
  import {printf} from './utils';
    /**
     * <amap-address :center="center"  :zoom="zoom" :radius="radius" @clickAddress="setAddress"></amap-address>
     * keywords 关键词 array
     * zoom 地图区域的缩放级别，取值范围是3-18 int
     * center 用于表示待标注点的坐标 array
     * radius 表示搜索的范围半径，单位为：米。 int
     * total 检索结果条数，默认为20 int
     * reduce 高度减少像素，用于空出头尾 int
     * @see http://lbs.amap.com/api/lightmap/guide/picker
     */
  export default {
    name: 'amap-address',
    data() {
      return {};
    },
    computed: {
      apiUrl() {
        let apiUrl = '//m.amap.com/picker/?keywords={0}&zoom={1}&center={2}&radius={3}&total={4}&key={5}';
        let keywords = this.keywords ? this.keywords.join(',') : '写字楼,小区,学校';
        let zoom = this.zoom ? this.zoom : 15;
        let center = this.center ? this.center.join(',') : '';
        let radius = this.radius ? this.radius : 1000;
        let total = this.total ? this.total : 20;
        return printf(apiUrl, keywords, zoom, center, radius, total, amapKey)
      }
    },
    props: {
      keywords: {
        type: Array
      },
      zoom: {
        type: Number
      },
      center: {
        type: Array
      },
      radius: {
        type: Number
      },
      total: {
        type: Number
      },
      reduce: {
        type: Number
      }
    },
    mounted() {
      this.$nextTick(function () {
        /**
         * 处理iframe高度
         */
        let width = Math.max(document.body.scrollWidth, document.body.clientWidth);
        let height = Math.max(document.body.scrollHeight, document.body.clientHeight);
        let iframe = document.getElementById('amap-address');
        let reduce = this.reduce ? this.reduce : 0;
        iframe.height = height - reduce;  // 这里通过hash传递b.htm的宽高
        /**
         * postMessage通讯
         */
        iframe.onload = function () {
          let url = window.location.protocol + '//m.amap.com/picker/';
          iframe.contentWindow.postMessage('hello', url);
        };
        window.addEventListener('message', event => {
//          alert('您选择了2:' + data.name + ',' + data.location + ',' + event.data.address);
          this.$emit('clickAddress', event.data); // 触发选择事件
        }, false);
      })
    }
  };
</script>
